/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ProviderStreamWorker;

import ProviderStreamWorker.Utils.ByteArray;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.misc.IOUtils;

/**
 *
 * @author fabualves
 */
public class StreamObject {

    private File file;
    private int chunksSize, totalOfChunks;

    public StreamObject(File file, int chunksSize) {
        this.file = file;
        this.chunksSize = chunksSize;
        this.totalOfChunks = (int) Math.ceil((float) file.length() / chunksSize);
    }

    /*
     * Monta o cabecalho do tipo: offset|total|size|filename de tamanhos 2|2|2|26 =
     * 32bytes
     */
    private byte[] getHeader(int order, int amount) {
        byte[] offset = BigInteger.valueOf(order).toByteArray();
        offset = ByteArray.zeroFillAllocate(offset, 2);
        byte[] total = BigInteger.valueOf(this.totalOfChunks).toByteArray();
        total = ByteArray.zeroFillAllocate(total, 2);
        byte[] size = BigInteger.valueOf(amount).toByteArray();
        size = ByteArray.zeroFillAllocate(size, 2);
        byte[] filename = this.file.getName().getBytes();
        filename = ByteArray.zeroFillAllocate(filename, 26);

        byte[] header = new byte[32];
        System.arraycopy(offset, 0, header, 0, 2);
        System.arraycopy(total, 0, header, 2, 2);
        System.arraycopy(size, 0, header, 4, 2);
        System.arraycopy(filename, 0, header, 6, 26);

        return header;
    }

    public ArrayList<byte[]> getChunks() {
        ArrayList<byte[]> chunks = new ArrayList<byte[]>();
        try {
            byte[] fileBytes = Files.readAllBytes(this.file.toPath());
            for (int i = 1; i <= this.totalOfChunks; i++) {
                byte[] content = new byte[chunksSize + 32];
                
                int amount;
                if(i < (this.totalOfChunks)){
                    amount = chunksSize;
                }
                else{
                    amount = (int)this.file.length()%chunksSize;
                }
                int offset = (i-1)*chunksSize;
                System.arraycopy(getHeader(i,amount),0,content,0,32);
                System.arraycopy(fileBytes, offset, content, 32, amount);
                chunks.add(content);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            //Logger.getLogger(StreamObject.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        return chunks;
    }
}
